#include "MJCardManager.h"
#include "MJCard.h"
#include <stdarg.h>
#include <cstdlib>
#include <cstring>

const int g_mj_typecount[MJCard::E_MJCard_TP_Count] = {
    36, 36, 36, 28, 8 };

const unsigned char g_mj_cards[MJCard::E_MJCard_TP_Count][36] = {
    {
        1,2,3,4,5,6,7,8,9,            // 万
        1,2,3,4,5,6,7,8,9,
        1,2,3,4,5,6,7,8,9,
        1,2,3,4,5,6,7,8,9,
    },
    {
        11,12,13,14,15,16,17,18,19,   // 条
        11,12,13,14,15,16,17,18,19,
        11,12,13,14,15,16,17,18,19,
        11,12,13,14,15,16,17,18,19,
    },
    {
        21,22,23,24,25,26,27,28,29,   // 筒
        21,22,23,24,25,26,27,28,29,
        21,22,23,24,25,26,27,28,29,
        21,22,23,24,25,26,27,28,29,
    },
    {
        31,32,33,34,35,36,37,         // 字牌 东南西北中发白
        31,32,33,34,35,36,37,
        31,32,33,34,35,36,37,
        31,32,33,34,35,36,37,
        0,0,0,0,0,0,0,0,
    },
    {
        41,42,43,44,45,46,47,48,      // 花牌 春夏秋冬梅兰竹菊
    },
};


MJCardManager::MJCardManager()
{
    m_left = 0;
}

MJCardManager::~MJCardManager()
{
    m_left = 0;
}

/*
 * removecount 为要排除的牌类型数量, 默认为0
 * 后面的可变参数为各个类型
 */
void MJCardManager::Shuffle(int removecount, ...)
{
    int _removetype[MJCard::E_MJCard_TP_Count] = {0};
    va_list arg_ptr;
    va_start( arg_ptr, removecount );
    for( int i=0; i<removecount; ++i )
    {
        int t = va_arg( arg_ptr, int );
        if( t < 0 || t > MJCard::E_MJCard_TP_Count )
            continue;
        _removetype[t] = 1;
    }

    m_left = 0;
    for( int t=0; t<MJCard::E_MJCard_TP_Count; ++t )
    {
        if( _removetype[t] == 1 )
            continue;
        memcpy( m_cards+m_left, &g_mj_cards[t][0], g_mj_typecount[t] );
        m_left += g_mj_typecount[t];
    }
    va_end( arg_ptr );
}

void MJCardManager::AddCards(unsigned char card, int count)
{
    for( int i=0; i<count; ++i )
    {
        m_cards[ m_left ] = card;
        ++m_left;
    }
}

int MJCardManager::Left()
{
    return m_left;
}

unsigned char MJCardManager::RandCard()
{
    if( m_left <= 0 )
    {
        return MJCard::E_MJCard_Invalid;
    }
    int idx = rand() % m_left;
    unsigned char card = m_cards[ idx ];

    // swap
    unsigned char tmp = m_cards[ m_left-1 ];
    m_cards[ m_left-1 ] = card;
    m_cards[ idx ] = tmp;

    --m_left;

    return card;
}


